package test.net;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

public class NetworkDumper
{
	public static void main(String[] args) throws SocketException
	{
		Enumeration<NetworkInterface> inters = NetworkInterface.getNetworkInterfaces();
		while(inters.hasMoreElements())
		{
			NetworkInterface inter = inters.nextElement();
			dump(inter, 0);
		}
	}

	private static void dump(NetworkInterface inter, int step) throws SocketException
	{
		String prefix = "";
		for(int i = 0; i < step; i ++)
		{
			prefix += "\t";
		}

		System.out.println(prefix + inter.getName() + "[" + bytesToMAC(inter.getHardwareAddress()) + "](" + inter.getDisplayName() + ")");
		Enumeration<InetAddress> addrs = inter.getInetAddresses();
		while(addrs.hasMoreElements())
		{
			InetAddress addr = addrs.nextElement();
			System.out.println(prefix + "\t" + addr.getHostAddress() + " : " + addr.getHostName());
		}

		Enumeration<NetworkInterface> inters = inter.getSubInterfaces();
		while(inters.hasMoreElements())
		{
			NetworkInterface subInter = inters.nextElement();
			dump(subInter, step + 1);
		}
	}

	private static String bytesToMAC(byte[] bytes)
	{
		if(bytes == null || bytes.length < 6)
		{
			return null;
		}

		String str = "";
		for(int i = 0; i < 6; i ++)
		{
			String s = Integer.toHexString(bytes[i]);
			if(s.length() == 1)
			{
				s = ":0" + s;
			}
			else if(s.length() > 2)
			{
				s = ":" + s.substring(s.length() - 2);
			}
			else
			{
				s = ":" + s;
			}

			str += s;
		}
		return str.substring(1);
	}
}
